package ds.project.test.logic;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import ds.project.datamodel.CustomException;
import ds.project.protocol.ServerRequests;
import ds.project.utils.FileUtils;

public class UploadFileThread extends Thread{
	
	private InetAddress serverAddress;	
	private int serverTcpPort;	
	private File uploadFile;
	private int fileId;
	
	public UploadFileThread(InetAddress serverAddress, int serverPort, File uploadFile, int fileId)
	{
		this.serverAddress = serverAddress;
		this.serverTcpPort = serverPort;
		this.uploadFile = uploadFile;
		this.fileId = fileId;
	}	
	
	public void run()
	{
		Socket socketToServer = null;
		PrintWriter out = null;
		BufferedReader in = null;		
		try{			
			socketToServer = new Socket(serverAddress, serverTcpPort);
			out = new PrintWriter(socketToServer.getOutputStream(), true);					
		    in = new BufferedReader(new InputStreamReader(socketToServer.getInputStream()));
		    out.println(ServerRequests.UPLOAD_FILE);
		    out.println(fileId + uploadFile.getName());
		}
		catch(IOException e){			
			e.printStackTrace();
			try {
				throw new CustomException(ClientErrorCodes.ERROR_CONNECTING_SERVER_TO_UPLOAD, e, "Error conectando con el servidor para el envio del archivo");
			} catch (CustomException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}		
		} 	
			
		try{
			FileUtils.WriteFile(uploadFile, socketToServer.getOutputStream());			
		    
		    in.close();
		    out.close();
		    socketToServer.close(); 
		}
		catch(IOException e)
		{
			e.printStackTrace();
			try {
				throw new CustomException(ClientErrorCodes.ERROR_UPLOADING_FILE, e, "Error enviando el archivo");
			} catch (CustomException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}	
		}		
	}	
}
